package com.analyse.stock.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.model.StockAnalyseFocusModel;
import com.analyse.stock.service.IBoardIndexDaily;
import com.analyse.stock.service.IFundFlowRealTime;
import com.analyse.stock.service.IStockAnalyseFocus;
import com.analyse.stock.service.IStockDailyRealTime;
import com.analyse.stock.utils.PublicHolidayUtil;
import com.analyse.stock.utils.StockStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 分时级别同步1min，开盘日时间区间内实时同步
 */
@Component
@Slf4j
public class RealTimeJob implements Job {

    @Autowired
    private IFundFlowRealTime fundFlowRealTime;

    @Autowired
    private IStockAnalyseFocus stockAnalyseFocus;

    @Autowired
    private IStockDailyRealTime stockDailyRealTime;

    @Autowired
    private IBoardIndexDaily boardIndexDaily;

    /**
     * 1分钟执行一次
     **/
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Date now = new Date();
        boolean isTrading = PublicHolidayUtil.isTradingDateTime("XSHE",now, StockStringUtil.tradingTimeFun);
        long time0 = System.currentTimeMillis();
        log.info("### 开始实时同步每日分时1min资金流向信息,当前时间：{} , 【{}】交易时间 ###",
                DateUtil.format(now, DatePattern.NORM_TIME_PATTERN),isTrading?"正在":"不在");
        if(!isTrading){
            return;
        }
        List<StockAnalyseFocusModel> focusList = stockAnalyseFocus.list();
        if(CollUtil.isEmpty(focusList)){
            log.info("### 在 【策略分析后的股票评估】表未发现需要关注的股票信息：{}", JSONObject.toJSONString(context.getJobDetail()));
            return;
        }
        String stockCodes = focusList.stream().map(StockAnalyseFocusModel::getStockCode).collect(Collectors.joining(StrUtil.COMMA));

        /**
         * 实时同步每日分时1min资金流向信息
         **/
        ThreadUtil.execAsync(() -> {
            Integer num = fundFlowRealTime.getLatest(stockCodes);
            log.info("### 结束--实时同步每日分时1min资金流向信息，股票 :{}, 共同步：{}条,耗时：{}毫秒 END",stockCodes,num,(System.currentTimeMillis()-time0));
        },true);


        /**
         * 实时同步日内分时1min数据
         **/
        ThreadUtil.execAsync(() -> stockDailyRealTime.getRealTime(stockCodes),true);

        /***
         * 拉取指数信息
         **/
        ThreadUtil.execAsync(() ->
            boardIndexDaily.pullIndexDailyList(
                    "000001,399001,399006,399005,000300,000016,000688,000300,000852,000905"),true
        );
    }
}
